from django.shortcuts import render
from django.views import View
from .models import Area
from django import http
from meiduo_mall.utils.response_code import RETCODE
from django.core.cache import cache
from . import constants


class AreaView(View):
    def get(self, request):
        # 接收
        area_id = request.GET.get('area_id')

        # 验证
        if area_id:
            # 获取缓存，如果有，则不需要进行mysql查询
            sub_data = cache.get('area_' + area_id)

            if sub_data is None:
                # 查询指定地区对象，并获取子级地址
                try:
                    area = Area.objects.get(pk=area_id)
                except:
                    return http.JsonResponse({
                        'code': RETCODE.PARAMERR,
                        'errmsg': '无效的地区编号'
                    })
                # 查询子级地区
                subs = area.subs.all()
                # 转换成json数据
                sub_list = []
                for sub in subs:
                    sub_list.append({
                        'id': sub.id,
                        'name': sub.name
                    })

                # 缓存
                sub_data = {
                    'id': area.id,
                    'name': area.name,
                    'subs': sub_list
                }
                cache.set('area_' + area_id, sub_data, constants.AREA_CACHE_EXPIRES)

            # 响应
            return http.JsonResponse({
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'sub_data': sub_data
            })
        else:
            # 读取缓存数据，如果没有，再查询
            province_list = cache.get('province_list')

            if province_list is None:
                # 查询所有的省
                provinces = Area.objects.filter(parent__isnull=True)
                # 转换成json数据
                province_list = []
                for province in provinces:
                    province_list.append({
                        'id': province.id,
                        'name': province.name
                    })

                # 缓存，优化
                cache.set('province_list', province_list, constants.AREA_CACHE_EXPIRES)

            # 响应
            return http.JsonResponse({
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'province_list': province_list
            })
